﻿(function ($) {
    /**
    * sp-UI namespace
    * @namespace sp
    * @name sp
    */
    var sp = window.sp = {
        version: "0.1",

        init: function () {
            
        },
        ajax: {
            call: function (ActionType, params, successCallback, errorCallback, async) {

                var serviceUrl = "/Services/AjaxServiceLocator.ashx";
                //if (!async) async = false;

                typeof (errorCallback) === 'undefined' ? errorCallback = function (a) { alert(a) } : '';

                $.ajax({
                    url: serviceUrl,
                    async: async,
                    data: $.extend({}, {}, {
                        ActionType: ActionType
                    }, params),
                    dataType: "json",
                    success: function (result) {
                        if (result.Success) {
                            if (typeof (successCallback) !== 'undefined') {
                                successCallback(result);
                            }
                            else {
                                alert("已经成功：" + result.Data.toString());
                            }
                        }
                        else {
                            errorCallback(result);
                        }
                    },
                    error: function () {
                        errorCallback("请求失败，请重试！");
                    }
                });
            }
        },
        //系统
        sys: {

    },
    ui: {
        pageDialog: function (url, title) {
            var iframe = $("<iframe></iframe>");
            iframe.attr("frameborder", 0);
            iframe.attr("scrolling", "no");
            iframe.attr("src", url);
            iframe.attr("width", "400px");
            iframe.attr("height", "250px");

            var dlg = $(iframe).dialog({
                autoOpen: false,
                modal: true,
                title: title,
                height: 350,
                width: 400,
                buttons: {
                    提交: function () {
                        $(this).contents().find("input[type=submit]").get(0).click();
                        //$(".ui-dialog-buttonset button:last").click();
                    },
                    取消: function () {

                        $(this).dialog("close");
                    }
                },
                close: function () {
                }
            });

            dlg.dialog("open");
        }
    },

    //数据验证
    validate: {

        updateTips: function (t) {
            var tips = $(".validateTips");
            tips.text(t).addClass("ui-state-highlight");
            setTimeout(function () {
                tips.removeClass("ui-state-highlight", 1500);
            }, 500);
        },
        checkLength: function (o, n, min, max) {
            o = $('[id$=' + o + ']');

            if (o.val().length > max || o.val().length < min) {
                o.addClass("ui-state-error");
                sp.validate.updateTips("Length of " + n + " must be between " +
					    min + " and " + max + ".");
                return false;
            } else {
                return true;
            }
        }
    },
    page: {
        backvalue: '-1',
        close: function () {
            var dlg = $("#dialog-form");
            if (dlg.length > 0) {
                dlg.dialog('close');
                sp.page.reload();
            }
            else
                window.close();

        },
        reload: function () {
            location.href = location.href;
        }
    },
    //通用区域
    utils: {
        body: $("body"),
        html: $("html"),
        window: $(window),
        document: $(document),
        zIndex: 1000,
        index: 0, // global instantiation index
        isTag: function (string) {
            return (/<([\w:]+)/).test(string);
        },
        isSelector: function (selector) {
            if (typeof selector !== "string") return false;
            for (var regex in $.expr.match) {
                if ($.expr.match[regex].test(selector) && !sp.utils.isTag(selector)) {
                    return true;
                };
            };
            return false;
        },
        inDom: function (selector, context) {
            if (typeof selector !== "string") return false;
            // jQuery: If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\.
            var selector = selector.replace(/(\!|\"|\$|\%|\&|\'|\(|\)|\*|\+|\,|\/|\;|\<|\=|\>|\?|\@|\[|\\|\]|\^|\`|\{|\||\}|\~)/gi, function (str, $1) {
                return "\\\\" + $1;
            });
            return $(selector, context).length > 0;
        },
        isArray: function (o) {
            return Object.prototype.toString.apply(o) === "[object Array]";
        },
        isUrl: function (url) {
            return ((/^((http(s)?|ftp|file):\/{2}(www)?|www.|((\/|\.{1,2})([\w]|\.{1,2})*\/)+|(\.\/|\/|\:\d))([\w\-]*)?(((\.|\/)[\w\-]+)+)?([\/?]\S*)?/).test(url));
        },
        avoidTextSelection: function () {
            $.each(arguments, function (i, e) {
                if ($.browser.msie) {
                    $(e).attr('unselectable', 'on');
                } else if ($.browser.opera) {
                    $(e).bind("mousedown", function () { return false; });
                } else {
                    $(e).addClass("sp-user-no-select");
                };
            });
            return;
        },
        hasOwn: function (o, property) {
            return Object.prototype.hasOwnProperty.call(o, property);
        },
        getStyles: function (element, style) {
            // Main browsers
            if (window.getComputedStyle) {
                return getComputedStyle(element, "").getPropertyValue(style);
                // IE
            } else {
                style = style.replace(/\-(\w)/g, function (str, $1) { return $1.toUpperCase(); });
                return element.currentStyle[style];
            }
        },
        //根据URL获取参数
        request: function (sName) {
            var sURL = new String(window.location);
            var sURL = document.location.href;
            var iQMark = sURL.lastIndexOf('?');
            var iLensName = sName.length;

            //retrieve loc. of sName
            var iStart = sURL.indexOf('?' + sName + '=') //limitation 1
            if (iStart == -1) {//not found at start
                iStart = sURL.indexOf('&' + sName + '=')//limitation 1
                if (iStart == -1) {//not found at end
                    return 0; //not found
                }
            }

            iStart = iStart + +iLensName + 2;
            var iTemp = sURL.indexOf('&', iStart); //next pair start
            if (iTemp == -1) {//EOF
                iTemp = sURL.length;
            }
            return sURL.slice(iStart, iTemp);
            sURL = null; //destroy String
        },
        //根据字符串获取参数
        requestparbyurl: function (url, paras) {
            var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
            var paraObj = {}
            for (i = 0; j = paraString[i]; i++) {
                paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
            }
            var returnValue = paraObj[paras.toLowerCase()];
            if (typeof (returnValue) == "undefined") {
                return "";
            } else {
                return returnValue;
            }
        },
        //转换成JSON
        parsetojason: function (o) {
            if (o == null)
                return "null";

            switch (o.constructor) {
                case String:
                    var s = o; // .encodeURI();
                    if (s.indexOf("}") < 0) s = '"' + s.replace(/(["\\])/g, '\\$1') + '"';
                    s = s.replace(/\n/g, "\\n");
                    s = s.replace(/\r/g, "\\r");
                    return s;
                case Array:
                    var v = [];
                    for (var i = 0; i < o.length; i++)
                        v.push(ParseToJson(o[i]));
                    if (v.length <= 0) return "\"\"";
                    return "" + v.join(",") + "";
                case Number:
                    return isFinite(o) ? o.toString() : ParseToJson(null);
                case Boolean:
                    return o.toString();
                case Date:
                    var d = new Object();
                    d.__type = "System.DateTime";
                    d.Year = o.getUTCFullYear();
                    d.Month = o.getUTCMonth() + 1;
                    d.Day = o.getUTCDate();
                    d.Hour = o.getUTCHours();
                    d.Minute = o.getUTCMinutes();
                    d.Second = o.getUTCSeconds();
                    d.Millisecond = o.getUTCMilliseconds();
                    d.TimezoneOffset = o.getTimezoneOffset();
                    return ParseToJson(d);
                default:
                    if (o["toJSON"] != null && typeof o["toJSON"] == "function")
                        return o.toJSON();
                    if (typeof o == "object") {
                        var v = [];
                        for (attr in o) {
                            if (typeof o[attr] != "function")
                                v.push('"' + attr + '": ' + ParseToJson(o[attr]));
                        }

                        if (v.length > 0)
                            return "{" + v.join(",") + "}";
                        else
                            return "{}";
                    }
                    alert(o.toString());
                    return o.toString();
            }
        },
        before: function (fun) {

        }

    },

    /**
    * sp-UI global events reference.
    */
    events: {
        LAYOUT: {
            CHANGE: "change"
        },
        VIEWPORT: {
            CHANGE: "change"
        },
        KEY: {
            ENTER: "enter",
            ESC: "esc",
            LEFT_ARROW: "left_arrow",
            UP_ARROW: "up_arrow",
            RIGHT_ARROW: "right_arrow",
            DOWN_ARROW: "down_arrow",
            BACKSPACE: "backspace"
        }
    }
};

/** 
* Utility to clone objects
* @function
* @name clon
* @param o Object to clone
* @returns object
* @memberOf sp
*/
sp.clon = function (o) {

    obj = {};

    for (x in o) {
        obj[x] = o[x];
    };

    return obj;
};


})($);

$(function () {
    sp.init();
});
